//
//  GaoLikeAnimationView.m
//  DuTe
//
//  Created by Gikki Ares on 2020/12/22.
//  Copyright © 2020 vgemv. All rights reserved.
//

/**
 * 实现原理
 * 创建一个imageView
 * 初始的缩放动画
 * 路径动画
 * 然后消失.
 */

#import "JsLikeAnimationManager.h"
#import "JsBundleManager.h"

@interface JsLikeAnimationManager()


@end


@implementation JsLikeAnimationManager

+ (JsLikeAnimationManager *)sharedInstance {
	static JsLikeAnimationManager * _sharedInstance;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_sharedInstance = [JsLikeAnimationManager new];
	});
	return _sharedInstance;
}

- (instancetype)init {
	if(self = [super init]) {
		[self commonInit];
	}
	return self;
}

- (void)commonInit {
}

/**
 fromView ,从该view的中间上方开始动画
 toView ???
 
 [viewA convertRect:viewA.subview toView:viewA.superview];
 */


- (void)showMoreLoveAnimationAtView:(UIView *)view fromPosition:(CGPoint)position {
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
	imageView.layer.position = position;
	NSArray *imgArr = @[@"Like_Orange.png",@"Like_Violet.png",@"Like_Green.png",@"Like_Blue.png",@"Like_Yellow.png",@"Like_red.png"];
	NSInteger img = arc4random()%6;
	UIImage * image = [JsBundleManager iconInBundleNamed:imgArr[img] inDir:@"Heart01"];
	imageView.image = image;
	[view addSubview:imageView];
	
	imageView.transform = CGAffineTransformMakeScale(0.01, 0.01);
	[UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
		imageView.transform = CGAffineTransformIdentity;
	} completion:nil];
	
	CGFloat duration = 3 + arc4random()%5;
	CAKeyframeAnimation *positionAnimate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
	positionAnimate.repeatCount = 1;
	positionAnimate.duration = duration;
	positionAnimate.fillMode = kCAFillModeForwards;
	positionAnimate.removedOnCompletion = NO;
	
	UIBezierPath *sPath = [UIBezierPath bezierPath];
	[sPath moveToPoint:position];
	CGFloat sign = arc4random()%2 == 1 ? 1 : -1;
	CGFloat controlPointValue = (arc4random()%50 + arc4random()%100) * sign;
	[sPath addCurveToPoint:CGPointMake(position.x, position.y - 300) controlPoint1:CGPointMake(position.x - controlPointValue, position.y - 150) controlPoint2:CGPointMake(position.x + controlPointValue, position.y - 150)];
	positionAnimate.path = sPath.CGPath;
	[imageView.layer addAnimation:positionAnimate forKey:@"heartAnimated"];
	
	
	[UIView animateWithDuration:duration animations:^{
		imageView.layer.opacity = 0;
	} completion:^(BOOL finished) {
		[imageView removeFromSuperview];
	}];
}

- (void)showMoreLoveAnimateFromView:(UIView *)fromView addToView:(UIView *)addToView {
	
	//计算
	CGRect loveFrame = [fromView.superview convertRect:fromView.frame toView:addToView];
	//layer.positon是center的数据.
	CGPoint position = CGPointMake(fromView.layer.position.x, loveFrame.origin.y - 30);
	[self showMoreLoveAnimationAtView:addToView fromPosition:position];
}


@end
